package cn.tpshion.vm.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@EnableAsync
@Configuration
public class ThreadConfig {

    @Bean
    public ThreadPoolTaskScheduler taskScheduler(){
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);                        // 线程池大小
        taskScheduler.setThreadNamePrefix("定时任务-");   // 线程名称
        taskScheduler.setAwaitTerminationSeconds(30);         // 等待时长
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);  // 调度器shutdown被调用时等待当前被调度的任务完成
        return taskScheduler;
    }

    @Bean
    public ThreadPoolTaskExecutor taskExecutor(){
        return buildExecutor(8, 16, 100, "异步任务-", null);
    }

    @Bean
    public ThreadPoolTaskExecutor msgTaskExecutor(){
        return buildExecutor(16, 32, 100, "消息任务-", null);
    }

    @Bean
    public ThreadPoolTaskExecutor sshExecutor(){
        return buildExecutor(8, 16, 50, "ssh任务-", null);
    }

    private ThreadPoolTaskExecutor buildExecutor(int core, int maxPool, int capacity, String name, RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setTaskDecorator(new MDCTaskDecorator());
        //设置核心线程数
        executor.setCorePoolSize(core);
        //设置最大线程数
        executor.setMaxPoolSize(maxPool);
        //配置队列大小
        executor.setQueueCapacity(capacity);
        //设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        //设置默认线程池名称
        executor.setThreadNamePrefix(name);
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //超出的任务
        executor.setRejectedExecutionHandler(rejectedExecutionHandler == null?
                new ThreadPoolExecutor.CallerRunsPolicy() : rejectedExecutionHandler);
        //执行初始化
        executor.initialize();
        return executor;
    }
}
